import os
from PIL import Image

class ImageOpacityAdjuster:
    def __init__(self, input_path=None, opacity=1.0, output_dir=r"C:\Users\33720\Desktop\temp"):
        self.input_path = input_path
        self.opacity = float(opacity)
        self.output_dir = output_dir

    # -------------------------
    # Setter 函数
    # -------------------------
    def set_input_path(self, input_path):
        """设置输入路径，可以是文件或文件夹"""
        if not os.path.exists(input_path):
            raise ValueError(f"输入路径不存在: {input_path}")
        self.input_path = input_path

    def set_opacity(self, opacity):
        """设置不透明度，范围 0.0 ~ 1.0"""
        if not (0.0 <= opacity <= 1.0):
            raise ValueError("不透明度必须在 0.0 ~ 1.0 之间")
        self.opacity = float(opacity)

    def set_output_dir(self, output_dir):
        """设置输出文件夹"""
        os.makedirs(output_dir, exist_ok=True)
        self.output_dir = output_dir

    # -------------------------
    # 内部工具函数
    # -------------------------
    def _adjust_image_opacity(self, img: Image.Image) -> Image.Image:
        if img.mode != "RGBA":
            img = img.convert("RGBA")
        r, g, b, a = img.split()
        a = a.point(lambda p: int(p * self.opacity))
        img = Image.merge("RGBA", (r, g, b, a))
        return img

    def _save_image(self, img: Image.Image, save_path: str):
        ext = os.path.splitext(save_path)[1].lower()
        # JPG 不支持透明度，用白底填充
        if ext in [".jpg", ".jpeg"]:
            bg = Image.new("RGB", img.size, (255, 255, 255))
            bg.paste(img, mask=img.split()[3])  # 用 alpha 通道作为遮罩
            bg.save(save_path, "JPEG")
        else:
            img.save(save_path)

        # -------------------------
        # 主执行函数
        # -------------------------
    def adjust_opacity(self):
        if not self.input_path:
            raise ValueError("请先设置 input_path")

        os.makedirs(self.output_dir, exist_ok=True)

        if os.path.isfile(self.input_path):
            self._process_single_file(self.input_path)
        else:
            for file_name in os.listdir(self.input_path):
                file_path = os.path.join(self.input_path, file_name)
                if os.path.isfile(file_path) and self._is_image_file(file_name):
                    self._process_single_file(file_path)
        print("🎨 不透明度调整完成！")
        return self.output_dir

    def getimgpathlist(self):
        imglist=[]
        os.makedirs(self.output_dir, exist_ok=True)

        if os.path.isfile(self.input_path):
            imglist.append(self.input_path)
        else:
            for file_name in os.listdir(self.input_path):
                file_path = os.path.join(self.input_path, file_name)
                imglist.append(file_path)
        return imglist

    from PIL import Image
    import os

    def adjust_opacity2(self):
        """
        批量调节图片不透明度（支持JPG、PNG等格式）
        自动处理无Alpha通道图片，避免黑底问题
        """
        imglist = self.getimgpathlist()
        result = []

        for image_path in imglist:
            # 打开图片
            img = Image.open(image_path).convert("RGBA")
            r, g, b, a = img.split()

            # 判断是否原图无透明通道（alpha全为255）
            alpha_is_full = all(px == 255 for px in a.getdata())

            # 调节Alpha通道
            a = a.point(lambda i: i * self.opacity)
            img = Image.merge("RGBA", (r, g, b, a))

            # 若原图无透明背景（如JPG），用白底合成，防止黑边
            if alpha_is_full:
                bg = Image.new("RGBA", img.size, (255, 255, 255, 255))
                img = Image.alpha_composite(bg, img)

            # 输出路径
            outputpath = os.path.join(self.output_dir, os.path.basename(image_path))

            # 自动选择保存格式（透明图保留PNG，否则JPG）
            ext = os.path.splitext(image_path)[1].lower()
            if ext in [".jpg", ".jpeg"]:
                # JPG 不支持透明，转成 RGB
                img = img.convert("RGB")
                outputpath = os.path.splitext(outputpath)[0] + ".jpg"
                img.save(outputpath, quality=95)
            else:
                img.save(outputpath)

            result.append(outputpath)
            print(f"✅ 已保存：{outputpath}（不透明度={self.opacity}）")

        return "\n".join(result)

    # -------------------------
    # 辅助函数
    # -------------------------
    def _is_image_file(self, filename):
        return filename.lower().endswith((".png", ".jpg", ".jpeg", ".bmp", ".webp", ".tiff"))

    def _process_single_file(self, file_path):
        try:
            with Image.open(file_path) as img:
                adjusted = self._adjust_image_opacity(img)
                base_name = os.path.basename(file_path)
                name, ext = os.path.splitext(base_name)
                new_path = os.path.join(self.output_dir, f"{name}_opacity{ext}")
                self._save_image(adjusted, new_path)
                print(f"✅ 处理成功: {new_path}")
        except Exception as e:
            print(f"❌ 处理失败: {file_path}，错误: {e}")

    # -------------------------
    # 使用示例
    # -------------------------
if __name__ == "__main__":
    adjuster = ImageOpacityAdjuster()
    adjuster.set_input_path(r"C:\Users\33720\Desktop\temp\imgnew")
    adjuster.set_opacity(0.6)
    adjuster.set_output_dir(r"C:\Users\33720\Desktop\temp\imgout")
    adjuster.adjust_opacity()